import uuid

from flask import jsonify

from db.app_user.app_user_tb import App_user
from db import db
from utils import rd_
from flask_restful import request, abort

from db.app_user import App_user
class Auth:
    def __encode_auth_token(self,user_key,login_time=None):
        if login_time:
            return rd_.set(uuid.uuid4().hex,user_key,login_time)
        return rd_.set(uuid.uuid4().hex,user_key,60*60*24*7)
    def __decode_auth_token(self,auto_token):
        id=rd_.get(auto_token)
        if not id:
            return Exception("token过期")
        return id
    """
    权限校验，token帮助类
    """
    def __call__(self, func):
        def innner(v,**kwargs):
            if 'Authorization' in request.headers:
                token=request.headers.get('Authorization')
                id=self.__decode_auth_token(token)
                if isinstance(id,Exception):
                    return abort(400,msg='token过期')
                try:
                    user=App_user.query.get(id)
                except:
                    return abort(401,msg='网不好')
                if not user:
                    return abort(402,msg='没有此用户')
                request.is_vip=user.is_vip
                request.token=token
                request.user=user
                return func(v,**kwargs)
            else:
                return abort(403,msg="没有请求头")
        return innner



class AdminAuth(object):
    pass